﻿namespace WMS6.SQLServerDAL
{
    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Data.Common;
    using System.Data.SqlClient;
    using WMS6.Common;
    using WMS6.DataEntity;
    using WMS6.DBUtility;
    using WMS6.IDAL;
    using WMS6.QueryEntity;

    public class BomDA : IBomDA
    {
        private string BOM_ONLY = "@BOM_ONLY";
        private string CREATED_BY = "@CREATED_BY";
        private string IS_ACTIVE = "@IS_ACTIVE";
        private string OWNER_ID = "@OWNER_ID";
        private string REMARK = "@REMARK";
        private string SKU_ID = "@SKU_ID";
        private string SQL_CHECK_BOM_ID_UNIQUE = " SELECT COUNT(1) FROM @_@BOM WHERE OWNER_ID = @OWNER_ID AND SKU_ID = @SKU_ID ";
        private string SQL_DELETE_BOM = " DELETE FROM @_@BOM WHERE OWNER_ID = @OWNER_ID AND SKU_ID = @SKU_ID ";
        private string SQL_INSERT_BOM = " INSERT INTO @_@BOM ( WH_ID, OWNER_ID, SKU_ID, BOM_ONLY, REMARK, IS_ACTIVE, CREATED_BY, CREATED_DATE, UPDATED_BY, UPDATED_DATE) VALUES ( @WH_ID, @OWNER_ID, @SKU_ID, @BOM_ONLY, @REMARK, @IS_ACTIVE, @CREATED_BY, GETDATE(), @UPDATED_BY, GETDATE() )  ";
        private string SQL_SELECT_ALL_BOM = " SELECT  ROWID, WH_ID, OWNER_ID, SKU_ID, BOM_ONLY, REMARK, IS_ACTIVE, TS, CREATED_BY, CREATED_DATE, UPDATED_BY, UPDATED_DATE  FROM  @_@BOM ";
        private string SQL_UPDATE_BOM = " UPDATE @_@BOM SET WH_ID = @WH_ID, BOM_ONLY = @BOM_ONLY, REMARK = @REMARK, IS_ACTIVE = @IS_ACTIVE, UPDATED_BY = @UPDATED_BY, UPDATED_DATE = GETDATE() WHERE OWNER_ID = @OWNER_ID AND SKU_ID = @SKU_ID  ";
        private string TS = "@TS";
        private string UPDATED_BY = "@UPDATED_BY";
        private string WH_ID = "@WH_ID";

        public bool CheckBomIDUnique(string bomID, string SkuID, string whLoginID)
        {
            SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@OWNER_ID", bomID), new SqlParameter("@SKU_ID", SkuID) };
            return (DBHelper.ExecuteScalar(CommandType.Text, this.SQL_CHECK_BOM_ID_UNIQUE.Replace("@_@", whLoginID), paras).ToString() == "1");
        }

        public bool CheckBomIDUnique(DataBase dataBase, DbTransaction tran, string bomID, string SkuID, string whLoginID)
        {
            SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@OWNER_ID", bomID), new SqlParameter("@SKU_ID", SkuID) };
            return (dataBase.ExecuteScalar(tran, CommandType.Text, this.SQL_CHECK_BOM_ID_UNIQUE.Replace("@_@", whLoginID), paras).ToString() == "1");
        }

        public int DeleteBom(List<string> bomID, List<string> SkuID, List<string> whLoginID)
        {
            int result = 0;
            DataBase dataBase = new DataBase();
            DbConnection conn = dataBase.connection;
            conn.Open();
            DbTransaction tran = conn.BeginTransaction();
            try
            {
                for (int i = 0; i < whLoginID.Count; i++)
                {
                    for (int j = 0; j < bomID.Count; j++)
                    {
                        SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@OWNER_ID", bomID[j]), new SqlParameter("@SKU_ID", SkuID[j]) };
                        result += dataBase.ExecuteNonQuery(tran, CommandType.Text, this.SQL_DELETE_BOM.Replace("@_@", whLoginID[i]), paras);
                    }
                }
                tran.Commit();
            }
            catch (SqlException sqlEx)
            {
                tran.Rollback();
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            finally
            {
                conn.Close();
            }
            return result;
        }

        public int DeleteBom(DataBase dataBase, DbTransaction tran, List<string> bomID, List<string> SkuID, List<string> whLoginID)
        {
            int result = 0;
            try
            {
                for (int i = 0; i < whLoginID.Count; i++)
                {
                    for (int j = 0; j < bomID.Count; j++)
                    {
                        SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@OWNER_ID", bomID[j]), new SqlParameter("@SKU_ID", SkuID[j]) };
                        result += dataBase.ExecuteNonQuery(tran, CommandType.Text, this.SQL_DELETE_BOM.Replace("@_@", whLoginID[i]), paras);
                    }
                }
            }
            catch (SqlException sqlEx)
            {
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            return result;
        }

        public DataSet GetAllBom(string whLoginID)
        {
            string sql = this.SQL_SELECT_ALL_BOM.Replace("@_@", whLoginID);
            return DBHelper.ExecuteDataSet(CommandType.Text, sql);
        }

        public DataSet GetAllBom(DataBase dataBase, DbTransaction tran, string whLoginID)
        {
            string sql = this.SQL_SELECT_ALL_BOM.Replace("@_@", whLoginID);
            return dataBase.ExecuteDataSet(tran, CommandType.Text, sql);
        }

        public BomInfo GetBomByID(string bomID, string SkuID, string whLoginID)
        {
            string sql = this.SQL_SELECT_ALL_BOM.Replace("@_@", whLoginID) + " WHERE OWNER_ID = @OWNER_ID AND SKU_ID = @SKU_ID  ";
            SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@OWNER_ID", bomID), new SqlParameter("@SKU_ID", SkuID) };
            BomInfo bomInfo = null;
            using (IDataReader reader = DBHelper.ExecuteReader(CommandType.Text, sql, paras))
            {
                if (reader.Read())
                {
                    bomInfo = new BomInfo((reader["ROWID"].ToString() != "") ? int.Parse(reader["ROWID"].ToString()) : 0, reader["WH_ID"].ToString(), reader["OWNER_ID"].ToString(), reader["SKU_ID"].ToString(), reader["BOM_ONLY"].ToString(), reader["REMARK"].ToString(), reader["IS_ACTIVE"].ToString(), (byte[]) reader["TS"], reader["CREATED_BY"].ToString(), (reader["CREATED_DATE"].ToString() != "") ? DateTime.Parse(reader["CREATED_DATE"].ToString()) : new DateTime(), reader["UPDATED_BY"].ToString(), (reader["UPDATED_DATE"].ToString() != "") ? DateTime.Parse(reader["UPDATED_DATE"].ToString()) : new DateTime());
                }
            }
            return bomInfo;
        }

        public BomInfo GetBomByID(DataBase dataBase, DbTransaction tran, string bomID, string SkuID, string whLoginID)
        {
            string sql = this.SQL_SELECT_ALL_BOM.Replace("@_@", whLoginID);
            SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@OWNER_ID", bomID), new SqlParameter("@SKU_ID", SkuID) };
            BomInfo bomInfo = null;
            IDataReader reader = dataBase.ExecuteReader(tran, CommandType.Text, sql, paras);
            if (reader.Read())
            {
                bomInfo = new BomInfo((reader["ROWID"].ToString() != "") ? int.Parse(reader["ROWID"].ToString()) : 0, reader["WH_ID"].ToString(), reader["OWNER_ID"].ToString(), reader["SKU_ID"].ToString(), reader["BOM_ONLY"].ToString(), reader["REMARK"].ToString(), reader["IS_ACTIVE"].ToString(), (byte[]) reader["TS"], reader["CREATED_BY"].ToString(), (reader["CREATED_DATE"].ToString() != "") ? DateTime.Parse(reader["CREATED_DATE"].ToString()) : new DateTime(), reader["UPDATED_BY"].ToString(), (reader["UPDATED_DATE"].ToString() != "") ? DateTime.Parse(reader["UPDATED_DATE"].ToString()) : new DateTime());
            }
            if (!reader.IsClosed)
            {
                reader.Close();
            }
            return bomInfo;
        }

        public DataSet GetBomByQueryList(List<string> sqlWhere, BomQueryEntity bomQuery, string whLoginID)
        {
            string temp = this.SQL_SELECT_ALL_BOM.Replace("@_@", whLoginID);
            for (int i = 0; i < sqlWhere.Count; i++)
            {
                if (i == 0)
                {
                    temp = temp + " WHERE " + sqlWhere[i].ToString();
                }
                else
                {
                    temp = temp + " AND " + sqlWhere[i].ToString();
                }
            }
            if (!bomQuery.IsGetAll)
            {
                temp = PagingHelper.GetPagingSQL(temp, bomQuery.CurrentPage, bomQuery.PageSize, bomQuery.SortField, bomQuery.SortDirection);
            }
            return DBHelper.ExecuteDataSet(CommandType.Text, temp);
        }

        public DataSet GetBomByQueryList(DataBase dataBase, DbTransaction tran, List<string> sqlWhere, BomQueryEntity bomQuery, string whLoginID)
        {
            string temp = this.SQL_SELECT_ALL_BOM.Replace("@_@", whLoginID);
            for (int i = 0; i < sqlWhere.Count; i++)
            {
                if (i == 0)
                {
                    temp = temp + " WHERE " + sqlWhere[i].ToString();
                }
                else
                {
                    temp = temp + " AND " + sqlWhere[i].ToString();
                }
            }
            if (!bomQuery.IsGetAll)
            {
                temp = PagingHelper.GetPagingSQL(temp, bomQuery.CurrentPage, bomQuery.PageSize, bomQuery.SortField, bomQuery.SortDirection);
            }
            return dataBase.ExecuteDataSet(tran, CommandType.Text, temp);
        }

        public int InsertBom(BomInfo bomInfo, List<string> whLoginID)
        {
            int result = 0;
            DataBase db = new DataBase();
            DbConnection conn = db.connection;
            conn.Open();
            DbTransaction tran = conn.BeginTransaction();
            try
            {
                for (int i = 0; i < whLoginID.Count; i++)
                {
                    bomInfo.WhID = whLoginID[i].Substring(0, whLoginID[i].Length - 1);
                    SqlParameter[] paras = this.Set_Bom_Parameters(bomInfo);
                    if (paras != null)
                    {
                        result += db.ExecuteNonQuery(tran, CommandType.Text, this.SQL_INSERT_BOM.Replace("@_@", whLoginID[i]), paras);
                    }
                }
                tran.Commit();
            }
            catch (SqlException sqlEx)
            {
                tran.Rollback();
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            finally
            {
                conn.Close();
            }
            return result;
        }

        public int InsertBom(DataBase dataBase, DbTransaction tran, BomInfo bomInfo, List<string> whLoginID)
        {
            int result = 0;
            try
            {
                for (int i = 0; i < whLoginID.Count; i++)
                {
                    bomInfo.WhID = whLoginID[i].Substring(0, whLoginID[i].Length - 1);
                    SqlParameter[] paras = this.Set_Bom_Parameters(bomInfo);
                    if (paras != null)
                    {
                        result += dataBase.ExecuteNonQuery(tran, CommandType.Text, this.SQL_INSERT_BOM.Replace("@_@", whLoginID[i]), paras);
                    }
                }
            }
            catch (SqlException sqlEx)
            {
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            return result;
        }

        private SqlParameter[] Set_Bom_Parameters(BomInfo bomInfo)
        {
            SqlParameter[] paramArray = new SqlParameter[] { new SqlParameter(this.WH_ID, SqlDbType.VarChar, 30), new SqlParameter(this.OWNER_ID, SqlDbType.VarChar, 20), new SqlParameter(this.SKU_ID, SqlDbType.VarChar, 50), new SqlParameter(this.BOM_ONLY, SqlDbType.VarChar, 1), new SqlParameter(this.REMARK, SqlDbType.VarChar, 500), new SqlParameter(this.IS_ACTIVE, SqlDbType.VarChar, 1), new SqlParameter(this.CREATED_BY, SqlDbType.VarChar, 20), new SqlParameter(this.UPDATED_BY, SqlDbType.VarChar, 20) };
            if (!string.IsNullOrEmpty(bomInfo.WhID))
            {
                paramArray[0].Value = bomInfo.WhID;
            }
            else
            {
                paramArray[0].Value = DBNull.Value;
            }
            paramArray[1].Value = bomInfo.OwnerID;
            paramArray[2].Value = bomInfo.SkuID;
            paramArray[3].Value = bomInfo.BomOnly;
            paramArray[4].Value = bomInfo.Remark;
            if (!string.IsNullOrEmpty(bomInfo.IsActive))
            {
                paramArray[5].Value = bomInfo.IsActive;
            }
            else
            {
                paramArray[5].Value = DBNull.Value;
            }
            paramArray[6].Value = bomInfo.CreatedBy;
            paramArray[7].Value = bomInfo.UpdatedBy;
            return paramArray;
        }

        public int UpdateBom(BomInfo bomInfo, List<string> whLoginID)
        {
            int result = 0;
            DataBase db = new DataBase();
            DbConnection conn = db.connection;
            conn.Open();
            DbTransaction tran = conn.BeginTransaction();
            try
            {
                for (int i = 0; i < whLoginID.Count; i++)
                {
                    bomInfo.WhID = whLoginID[i].Substring(0, whLoginID[i].Length - 1);
                    SqlParameter[] paras = this.Set_Bom_Parameters(bomInfo);
                    if (paras != null)
                    {
                        result += db.ExecuteNonQuery(tran, CommandType.Text, this.SQL_UPDATE_BOM.Replace("@_@", whLoginID[i]), paras);
                    }
                }
                tran.Commit();
            }
            catch (SqlException sqlEx)
            {
                tran.Rollback();
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            finally
            {
                conn.Close();
            }
            return result;
        }

        public int UpdateBom(DataBase dataBase, DbTransaction tran, BomInfo bomInfo, List<string> whLoginID)
        {
            int result = 0;
            try
            {
                for (int i = 0; i < whLoginID.Count; i++)
                {
                    bomInfo.WhID = whLoginID[i].Substring(0, whLoginID[i].Length - 1);
                    SqlParameter[] paras = this.Set_Bom_Parameters(bomInfo);
                    if (paras != null)
                    {
                        result += dataBase.ExecuteNonQuery(tran, CommandType.Text, this.SQL_UPDATE_BOM.Replace("@_@", whLoginID[i]), paras);
                    }
                }
            }
            catch (SqlException sqlEx)
            {
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            return result;
        }
    }
}

